 package com.bnzj.core.webmvc.listener;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.boot.autoconfigure.web.ServerProperties;

import com.bnzj.core.config.CoreProperties;

/**
 * 把属性注入到ServletContext，方便在controller中使用
 * @author barry
 * @date 2019/09/18
 */
 @WebListener
 public class BnzjServletContextInitializer implements ServletContextListener {
     
     @Resource
     private CoreProperties coreProperties;
     
     @Resource
     private ServerProperties serverProperties;
     
     @Override
     public void contextInitialized(ServletContextEvent event) {
         ServletContext servletContext = event.getServletContext();
         servletContext.setAttribute("serverProperties", serverProperties);
         String contextPath = serverProperties.getServlet().getContextPath();
         String basePath = contextPath.isEmpty() ? "/" : contextPath;
         String fileServerUrl = coreProperties.getFileServer().getUrl();
         fileServerUrl = fileServerUrl.substring(0, fileServerUrl.lastIndexOf("/"));
         servletContext.setAttribute("fileServerUrl", fileServerUrl);
         servletContext.setAttribute("version", coreProperties.getVersion());
         servletContext.setAttribute("basePath", basePath);
         servletContext.setAttribute("path", basePath);
     }

     @Override
     public void contextDestroyed(ServletContextEvent sce) {
         
     }
 }
